from rest_framework import status
from rest_framework.generics import GenericAPIView, ListAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from meiduo_admin.serializers.users import AdminAuthSerializer, UserInfoSerializer

# 2 定制视图类
from users.models import User


class AdminAuthAPIView(APIView):

    # 用户登录方法
    # POST /meiduo_admin/authorizations/
    def post(self, request):
        # 反序列化
        serializer = AdminAuthSerializer(data=request.data)
        # 数据校验
        serializer.is_valid(raise_exception=True)
        # 生成token
        serializer.save()
        # 序列化操作
        return Response(serializer.data,status=status.HTTP_201_CREATED)

# # 定制用户获取信息的逻辑
# class UserInfoView(APIView):
#     # 1 管理员认证
#     permission_classes = [IsAdminUser]
#     # 2 定制请求方法 - get
#     def get(self, request):
#         # 2-1 数据的获取 - keyword 数据的筛选
#         keyword = request.query_params.get('keyword')
#         if keyword:
#             users = User.objects.filter(username__contains=keyword, is_staff=False)
#         else:
#             users = User.objects.filter(is_staff=False)
#         # 2-2 序列化操作 - 用户users 是多数据对象
#         serializer = UserInfoSerializer(instance=users, many=True)
#         # 2-3 数据返回
#         return Response(serializer.data)

# 重写用户获取信息的逻辑 - GenericAPIview
# class UserInfoView(GenericAPIView):
#     permission_classes = [IsAdminUser]
#     # 1 序列化类的指定
#     serializer_class = UserInfoSerializer
#
#     # 2-1 因为数据集的获取需要借助于get_queryset，而默认的方法满足不了要求
#     def get_queryset(self):
#         # 2-1 数据的获取 - keyword 数据的筛选
#         keyword = self.request.query_params.get('keyword')
#         if keyword:
#             users = User.objects.filter(username__contains=keyword, is_staff=False)
#         else:
#             users = User.objects.filter(is_staff=False)
#         return users
#
#     # 2 数据集的定制
#     def get(self, request):
#         # 数据的获取
#         users = self.get_queryset()
#         # 2-2 序列化操作 - 用户users 是多数据对象
#         serializer = UserInfoSerializer(instance=users, many=True)
#         # 2-3 数据返回
#         return Response(serializer.data)


# 重写用户获取信息的逻辑 - ListAPIView
class UserInfoView(ListAPIView):
    permission_classes = [IsAdminUser]
    # 1 序列化类的指定
    serializer_class = UserInfoSerializer

    # 2-1 因为数据集的获取需要借助于get_queryset，而默认的方法满足不了要求
    def get_queryset(self):
        # 2-1 数据的获取 - keyword 数据的筛选
        keyword = self.request.query_params.get('keyword')
        if keyword:
            users = User.objects.filter(username__contains=keyword, is_staff=False)
        else:
            users = User.objects.filter(is_staff=False)
        return users

